import React, { Component } from 'react'
import DetailList from './detailList'
import getTime from '../../until/getTime'
import axios from 'axios'

export default class List extends Component {

    state={
        list:[],
        DetailIsShow:false,
        detailList:[],
        readId:null
    }

    // 控制详情列表页面的显示隐藏，更新详情页面需要展示的数据数组及对应id
    setDetailIsShow = (arr=[],id=null) => this.setState({DetailIsShow:!this.state.DetailIsShow,detailList:arr,readId:id})


    // 获取未读条数
    getReadNum= arr => arr.filter(item=>item.isRead === 1).length
    

    // 点击全部已读
    setAllRead =()=> axios.get('/list/read').then(data=>{

        if(data.data.code === 1){
            alert('全部已读')
            this.initData(data.data.data)
        }
    })


    // 对请求回来的数据做时间倒序处理 并更新list

    initData = list =>{

        list.forEach(item=> item.sub = [...item.sub.sort((a,b)=>getTime(b.date)-getTime(a.date))])
        this.setState({list})
    }

 
    render() {
        const {list,DetailIsShow,detailList,readId} = this.state
        return (
            <div className="newsList">
                {/* 头部 */}
                <div className="header">
                    <span className="iconfont icon-fanhui" onClick={this.props.setListIsSHow} ></span>
                    消息列表
                    <span className="all_read" onClick={()=>this.setAllRead()}>标记全部已读</span>
                </div>

                {/* 列表 */}
                <div className="list_body">
                {
                    list.length>0&&list.map(item=>{
                        return <div key={item.id} onClick={()=>this.setDetailIsShow(item.sub,item.id)}>
                                <div>{item.type}<span>{item.sub[0].time}</span></div>
                                <p>{item.sub[0].title}</p>
                                {
                                    this.getReadNum(item.sub)? <strong>{this.getReadNum(item.sub)}</strong>:null
                                }   
                            </div>
                    })
                }
                </div>
                {
                    DetailIsShow?<DetailList initData={this.initData} id={readId} detailList={detailList} setDetailIsShow={this.setDetailIsShow}/>:null
                }
               
               
            </div>
        )
    }

    // 初始化请求列表数据
    componentDidMount(){
        axios.get('/list').then(data=>this.initData(data.data.data))
    }
}
    

